// 封装ajax请求，方便统一处理接口返回值

import Vue from "vue";
import axios from "axios";
import apiHelper from "./apiHelper";
import webDbHelper from "./webDbHelper";

const qs = require('qs');
const appFetch = function (params, success, error) {
    var oldUrl = params.url;

    if (params === undefined) {
        console.error("必须传递参数");
        return false;
    }

    //去配置文件查找uri  增加筛选条件http--如果没有http 就进行封装方法修饰链接，有就直接用-用于直接填写api的控件
    if (params.url.toLocaleLowerCase().indexOf('http') < 0) {
        params.url = apiHelper.getApi(params.url);
    }
    params.withCredentials = false;
    if (!params.isUpload) {
        //设置默认header
        var defaultHeaders = {
            'Content-Type': 'application/x-www-form-urlencoded'
        };
    } else {
        var defaultHeaders = {
            "Content-Type": "multipart/form-data"
        };
    }


    if (params.headers) {
        params.headers = {
            ...defaultHeaders,
            ...params.headers
        };
    } else {
        params.headers = defaultHeaders;
    }

    //参数统一用data,syf修改
    if (params.method.toLowerCase() == 'get') {
        params.params = params.data;
        delete params.data
    }
    if (!params.isUpload && params.data) {
        params.data = qs.stringify(params.data);
    }

    //统一设置请求数据转换
    let nowAxios = axios.create({
        transformRequest: function (data) {
            return data;
        }
    });

    //限流e
    let rateLimitCode = [-5001, -5002, -5003, -5004, -5005, -5101];
    let reLoginCode = -5100;
    return nowAxios(params)
        .then(function (response) {
            let d = response.data || {};

            d.code = +d.code;
            if (reLoginCode == d.code) {
                webDbHelper.clearLAll();

                Vue.prototype.appRouter.go(0)
            }
            if (rateLimitCode.includes(d.code)) {
                Vue.prototype.appRouter.replace({path: '/common/busy'})
            } else {
                success(response.data);
            }
        })
        .catch(function (err) {
            console.error(err, 'API ' + oldUrl);
            error && error(err);
        });
}

Vue.prototype.appFetch = appFetch;

export {appFetch};
